// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    const {
        sourceId,
        targetId,
        delSource = true,
        sameOrigin = true
    } = event;
    console.log(event);
    const promiseList=[]
    //获取源/目标任务数据
    const sourceMission=await db.collection('mission').doc(sourceId).field({
        front:true,
        back:true,
        userId:true,
        name:true
    }).get().then(a=>a.data);
    const targetMission=await db.collection('mission').doc(targetId).field({
        front:true,
        back:true,
        userId:true,
        name:true
    }).get().then(a=>a.data);
    if(!sourceMission||!targetMission) return new Error('获取数据失败');
    if(sameOrigin&&sourceMission.userId!==targetMission.userId) return new Error('任务非同源');
    //将后置任务数据合并进目标任务
    targetMission.back.push(...sourceMission.back);
    targetMission.back=[...new Set(targetMission.back)]
    promiseList.push(new Promise(resolve=>{
        db.collection('mission').doc(targetId).update({
            data:{
                back:db.command.set(targetMission.back)
            }
        }).then(resolve)
    }))
    //遍历源任务后置目标 刷新前置任务
    for (const id of sourceMission.back) {
        promiseList.push(new Promise(resolve=>{
            db.collection('mission').doc(id).field({front:true}).get().then(res=>{
                if(!res.data||!res.data.front) resolve();
                const index=res.data.front.indexOf(sourceId);
                if(index>=0){
                    db.collection('mission').doc(id).update({
                        data:{
                            front:{
                                [index]:targetId
                            }
                        }
                    }).then(resolve)
                }else{
                    resolve();
                }
            })
        }))
    }
    //删除源任务
    if(delSource){
        promiseList.push(new Promise(resolve=>{
            db.collection('mission').doc(sourceId).remove().then(res=>{
                resolve(res);
            })
        }))
    }
    promiseList.push(new Promise(resolve=>{
        cloud.callFunction({
            name: 'logMission',
            data: {
                userId:wxContext.OPENID,
                missionId: targetId,
                description: `将${sourceMission.name}合并至该任务`
            }
        }).then(resolve)
    }))
    return await Promise.all(promiseList);
}